import * as fs from "node:fs"
import * as path from "node:path"
import { KNumTree, pad0 } from "@coldcloude/kai2"
import { Pixel } from "../hp3-img.js";
import { loadPng, savePng } from "../hp3-png.js";

const inputDir = "E:\\tmp\\src";
const outputDir = "E:\\tmp\\out";

const dirEntries = fs.readdirSync(inputDir, { withFileTypes: true });

for (const dirEntry of dirEntries) {
    const subInputDir = path.join(inputDir, dirEntry.name);
    const subOutputDir = path.join(outputDir, dirEntry.name);

    if (dirEntry.isDirectory()) {
        if(!fs.existsSync(subOutputDir)){
            fs.mkdirSync(subOutputDir);
        }
        const fileMap = new KNumTree<string>();
        const files = fs.readdirSync(subInputDir);
        for(const file of files){
            const fn = path.basename(file);
            const s = fn.indexOf("(");
            const e = fn.indexOf(")");
            if(s>0&&e>s){
                const index = Number.parseInt(fn.substring(s+1,e));
                if(index>0){
                    fileMap.set(index,fn);
                }
            }
        }
        var id = 0;
        fileMap.foreach((index,fn)=>{
            const inputFile = path.join(subInputDir,fn);
            const src = loadPng(inputFile);
            const w = src.width;
            const h = src.height;
            const hw = w>>1;
            let l = 0;
            let r = w-1;
            for(; l<hw; l++){
                const p = src.pixels[l];
                if(!(p.r===59&&p.g===59&&p.b===59)){
                    break
                }
            }
            for(; r>hw; r--){
                const p = src.pixels[r];
                if(!(p.r===59&&p.g===59&&p.b===59)){
                    break
                }
            }
            const areas:number[][] = []
            if(l<hw&&r>hw){
                if(r-l>h){
                    //two image
                    areas.push([hw,r+1],[l,hw]);
                }
                else{
                    areas.push([l,r+1]);
                }
            }
            for(const dsde of areas){
                const ds = dsde[0];
                const de = dsde[1];
                const dw = de-ds;
                const pixels = new Array<Pixel>(dw*h);
                for(let y=0; y<h; y++){
                    for(let x=0; x<dw; x++){
                        pixels[y*dw+x] = src.pixels[y*w+x+ds];
                    }
                }
                id++;
                const outputFile = path.join(subOutputDir,pad0(id,3)+".png");
                savePng(dw,h,pixels,outputFile);
                if(id%10===0){
                    console.error("output "+id+" pages for "+dirEntry.name);
                }
            }
        });
        console.error("output "+dirEntry.name+" done");
    }
}
